class Solution:
    def maximalNetworkRank(self, n: int, roads: list) -> int:
        adj = [set() for _ in range(n)]
        degrees = [0 for _ in range(n)]
        for i in range(len(roads)):
            road = roads[i]
            adj[road[0]].add(road[1])
            adj[road[1]].add(road[0])
            degrees[road[0]] += 1
            degrees[road[1]] += 1
        ans = 0
        for i in range(len(degrees)):
            for j in range(i + 1, len(degrees)):
                s = degrees[i] + degrees[j]
                if j in adj[i]:
                    s -= 1
                ans = max(ans, s)

        return ans
